package service

import (
	"api/internal/svc"
	"api/model/business"
	"api/utils"
	"context"
	"encoding/json"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"strconv"
)

// 订单服务
type BusinessService struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewBusinessService(ctx context.Context, svcCtx *svc.ServiceContext) *BusinessService {
	return &BusinessService{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

//type Business struct {
//	Id int64 `json:"id"`
//}

var (
	BUSS_LOGIN = "busLogin" // hash 商户登录

	BUSS_SOCKET = "busSocket"

	MONEY_TODAY       = "moneyToday"      // 今日交易金额
	MONEY_YESTERDAY   = "moneyYesterday"  // 昨日交易金额
	PAID_SERVICE_FEED = "paidServiceFeed" // 已支付服务费
	MONEY_ALL         = "moneyAll"        // 总交易金额

	DISCOUNT_SALE = "discountSale" // HASH  会员卡销售数量

)

// 根据商户id获取微信商户号
func (busService *BusinessService) GetWxCodeByBusId(redis redis.Conn, busId int) {

}

// 根据商户id获取支付宝商户号
func (busService *BusinessService) GetAliCodeByBusId(redis redis.Conn, busId int) {

}

// 保存商户

func (busService *BusinessService) SaveBusiness(redis redis.Conn, business *business.Business) {

}

// 根据商户id获取商户登录信息
func (busService *BusinessService) GetBussById(redis redis.Conn, id int) *business.Business {
	field := "business:" + strconv.Itoa(id)

	ret, _ := redis.Do("HGET", BUSS_LOGIN, field)
	if ret != nil {
		var res business.Business
		json.Unmarshal(ret.([]byte), &res)
		return &res
	} else {
		return nil
	}
}

// 商户socket绑定
func (busService *BusinessService) SaveBussSocket(redis redis.Conn, phone string, fd string) {
	field := "business:" + phone
	redis.Do("HSET", BUSS_SOCKET, field, fd)
}

// 获取商户socket
func (busService *BusinessService) GetBussSocket(redis redis.Conn, phone string) (string, error) {
	field := "business:" + phone
	ret, _ := redis.Do("HGET", BUSS_SOCKET, field)
	if ret != nil {
		return ret.(string), nil
	} else {
		return "", fmt.Errorf("socket未找到 phone:" + phone)
	}
}

// 商户登录
func (busService *BusinessService) BusLogin(redis redis.Conn, phone string, password string) (string, error) {
	var conn = sqlx.NewMysql(busService.svcCtx.Config.DataSource)
	busModel := business.NewBusinessModel(conn)
	bus, _ := busModel.FindByPhone(busService.ctx, phone, password)
	if bus == nil {
		// 数据不存在
		return "", fmt.Errorf("商家不存在")
	}

	// 入redis
	d := &business.Business{
		Id:    bus.Id,
		Phone: bus.Phone,
	}
	field := "business:" + strconv.Itoa(int(bus.Id))
	jsonD, _ := json.Marshal(d)
	token, _ := utils.GetJwtToken(busService.svcCtx.Config.Auth.AccessSecret, busService.svcCtx.Config.Auth.AccessExpire, string(jsonD))
	redis.Do("HSET", BUSS_LOGIN, field, jsonD)
	// 返回信息
	return token, nil
}

// 获取登录商家信息
func (busService *BusinessService) GetLoginBusinessInfo() *business.Business {
	payload := busService.ctx.Value("payload").(string)
	loginD := &business.Business{}
	json.Unmarshal([]byte(payload), loginD)
	return loginD
}

// 修改今日交易金额
func (busService *BusinessService) UpdateMoneyToday(redis redis.Conn, phone string, amount int) {
	redis.Do("HINCRBY", MONEY_TODAY, phone, amount)
}

// 获取今日交易金额
func (busService *BusinessService) GetMoneyToday(redis redis.Conn, phone string) int {
	ret, _ := redis.Do("HGET", MONEY_TODAY, phone)
	if ret != nil {
		str := string(ret.([]byte))
		v, _ := strconv.Atoi(str)
		return v
	} else {
		return 0
	}
}

// 修改总交易金额
func (busService *BusinessService) UpdateMoneyAll(redis redis.Conn, phone string, amount int) {
	redis.Do("HINCRBY", MONEY_ALL, phone, amount)
}

// 获取总交易金额
func (busService *BusinessService) GetMoneyAll(redis redis.Conn, phone string) int {
	ret, _ := redis.Do("HGET", MONEY_ALL, phone)
	if ret != nil {
		str := string(ret.([]byte))
		v, _ := strconv.Atoi(str)
		return v
	} else {
		return 0
	}
}

// 修改会员卡销售数量
// discountId 会员卡ID
func (busService *BusinessService) SaveDiscountSale(redis redis.Conn, discountId int64) {
	redis.Do("HINCRBY", DISCOUNT_SALE, discountId, 1)
}

// 根据会员卡id列表获取会员卡销售数量列表
// ids 会员卡id列表
// return  id=>销售数量
func (busService *BusinessService) GetDiscountSaleListByIds(redis redis.Conn, ids []int64) (res map[int64]int) {
	luaScript := fmt.Sprintf(`
			local res = {}
			for _, id in ipairs(KEYS) do
				local field = id
				local ret = redis.call("HGET", '%s', field)
		    	-- local d = {}  
				if ret then
					res[id] = tonumber(ret)
				else
					res[id] = 0
				end
				--table.insert(res, d)
			end
			
			return cjson.encode(res)
		`, DISCOUNT_SALE)
	var luaArgs []interface{}
	luaArgs = append(luaArgs, luaScript) // 第一个参数是 Lua 脚本
	luaArgs = append(luaArgs, len(ids))  // 第二个参数是 ids 的长度
	for _, id := range ids {
		luaArgs = append(luaArgs, id)
	}
	// 执行 Lua 脚本
	ret, err := redis.Do("EVAL", luaArgs...)

	if err != nil {
		return nil
	}
	if err := json.Unmarshal(ret.([]byte), &res); err != nil {
		return res
	} else {
		return nil
	}
}

// 删除会员卡销售数量
func (busService *BusinessService) DelDiscountSale(redis redis.Conn, discountId int64) {
	redis.Do("HDEL", DISCOUNT_SALE, discountId)
}
